package example.tallydemo.MyFragment;


import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.Toast;

import com.github.mikephil.charting.charts.PieChart;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import example.tallydemo.MyActivity.ShowDetailActivity;
import example.tallydemo.MyAdapter.MyListAdapter;
import example.tallydemo.MyContextMeau.TzhContextMenu;
import example.tallydemo.MyEntity.AccountBook;
import example.tallydemo.MyEntity.AccountManager;
import example.tallydemo.MyEntity.MyPieChart;
import example.tallydemo.MyTools.MyTimeTool;
import example.tallydemo.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class AnalyseFragment extends MyBaseFragment
{


    AccountManager accountManager = null;
    MyListAdapter myListAdapter = null;
    MyTimeTool myTimeTool;
    ListView listView;
    MyPieChart myPieChart;
    PieChart mPieChart;
    Button selectTimeBegin;
    Button selectTimeEnd;
    Button changeType;
    View view;
    public Date startDate;
    public Date stopDate;
    List<AccountBook> books = new ArrayList<>();
    List<AccountBook> inputbooks = new ArrayList<>();
    List<AccountBook> expendbooks = new ArrayList<>();
    Boolean flag = false;

    public void setFragment(AccountManager accountManager)
    {
        this.accountManager = accountManager;
    }

    public AnalyseFragment()
    {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_analyse, container, false);
        onCreate(view);
        return view;
    }



    public void onCreate(View view)
    {

        //按钮初始化
        selectTimeBegin = view.findViewById(R.id.id_analyse_begin);
        selectTimeEnd = view.findViewById(R.id.id_analyse_end);
        changeType = view.findViewById(R.id.id_analyse_button);
        changeType.setText("支出");

        myTimeTool = new MyTimeTool();


        //初始化时间显示
        initDate();

        mPieChart = view.findViewById(R.id.id_pie_chart);
        myListAdapter = new MyListAdapter(getContext());
        listView = view.findViewById(R.id.id_analyse_listview);
        listView.setAdapter(myListAdapter);

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
        {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
            {
                AccountBook it = (AccountBook) myListAdapter.getItem(position);
                onItemLongClicked(view,it);
                return false;
            }
        });


        //按钮响应
        selectTimeBegin.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                selectTimeStart(v);
            }
        });
        selectTimeEnd.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                selectTimeStop(v);
            }
        });
        changeType.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                setChangeType(v);
            }
        });

        if (myListAdapter != null)
        {
            myListAdapter.delAll();
            inputbooks.clear();
            expendbooks.clear();
        }
        setDate(accountManager.queryTime(startDate,stopDate));

    }

    public void setDate(List<AccountBook> books)
    {
        for (AccountBook it:books)
        {
            if (it.getType())
            {
                inputbooks.add(it);
            }
            else
            {
                Log.d("支出测试",String.valueOf(it.getMoney()));
                expendbooks.add(it);
            }
        }
        if (flag)
        {
            myListAdapter.addBooks(inputbooks);
            myPieChart = new MyPieChart(mPieChart,inputbooks);
            myPieChart.setData("收入");
        }
        else
        {
            myListAdapter.addBooks(expendbooks);
            myPieChart = new MyPieChart(mPieChart,expendbooks);
            myPieChart.setData("支出");
        }

        myPieChart.initPieChart();
        myPieChart.update();
        myListAdapter.notifyDataSetChanged();


    }

    public void clearDate()
    {
        inputbooks.clear();
        expendbooks.clear();
        myListAdapter.delAll();
        myPieChart.clearPieChart();
    }


    public void onDetailItem(View view,AccountBook it)
    {
        Intent intent = new Intent(getContext(), ShowDetailActivity.class);

        if (it.getType())
        {
            intent.putExtra("type","收入");
        }
        else
        {
            intent.putExtra("type","支出");
        }
        intent.putExtra("id",it.getId());
        intent.putExtra("origin",it.getOrigin());
        intent.putExtra("classify",it.getClassify());
        intent.putExtra("money",String.valueOf(it.getMoney()));
        intent.putExtra("date",myTimeTool.DateToString(it.getDate()));
        intent.putExtra("introduction",it.getIntroduction());
        startActivity(intent);
    }

    private void onItemLongClicked(final View view, final AccountBook book)
    {
        TzhContextMenu contextMenu = new TzhContextMenu();
        contextMenu.addContextItem("删除", "remove");
        contextMenu.addContextItem("详细", "detail");

        contextMenu.show(getContext(),view,view.getWidth()/2,-view.getHeight()/2);//显示位置
        contextMenu.listener = new TzhContextMenu.OnContextMenuItemClickedListener()
        {
            @Override
            public void onContextMenuItemClicked(String option, String value)
            {
                if (value.equals("remove"))
                {
                    onDelItem(view,book);
                }else if (value.equals("detail"))
                {
                    onDetailItem(view,book);
                }
            }
        };
    }

    public void onDelItem(View view1,AccountBook it)
    {
        accountManager.delete(it);
        clearDate();
        setDate(accountManager.queryTime(startDate,stopDate));
    }


    public void update()
    {
        if (!(inputbooks.size() == 0 && expendbooks.size() == 0))
        {
            clearDate();
            setDate(accountManager.queryTime(startDate,stopDate));
        }
    }

    public void selectTimeStart(View view)
    {
        Calendar calendar = Calendar.getInstance();
        new DatePickerDialog(getContext(), R.style.MyDatePickerDialogTheme,
                new DatePickerDialog.OnDateSetListener()
        {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth)
            {
                startDate = myTimeTool.setDateStart(year,month+1,dayOfMonth);
                if (judge(startDate,stopDate))
                {
                    selectTimeBegin.setText(new StringBuilder().append(year).append("-")
                            .append((month + 1) < 10 ? "0" + (month + 1) : (month + 1))
                            .append("-")
                            .append((dayOfMonth < 10) ? "0" + dayOfMonth : dayOfMonth));
                    clearDate();
                    setDate(accountManager.queryTime(startDate,stopDate));
                }
                else
                {
                    Toast.makeText(getContext(), "开始时间大于结束时间", Toast.LENGTH_SHORT).show();
                    startDate = myTimeTool.getFirstDate();
                    selectTimeBegin.setText(myTimeTool.DateToString(startDate));
                }
            }
        },calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();

    }

    public void selectTimeStop(View view)
    {

        Calendar calendar = Calendar.getInstance();
        new DatePickerDialog(getContext(), R.style.MyDatePickerDialogTheme, new DatePickerDialog.OnDateSetListener()
        {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth)
            {

                stopDate = myTimeTool.setDateStart(year,month+1,dayOfMonth);
                if (judge(startDate,stopDate))
                {
                    selectTimeBegin.setText(new StringBuilder().append(year).append("-")
                            .append((month + 1) < 10 ? "0" + (month + 1) : (month + 1))
                            .append("-")
                            .append((dayOfMonth < 10) ? "0" + dayOfMonth : dayOfMonth));
                    clearDate();
                    setDate(accountManager.queryTime(startDate,stopDate));
                }
                else
                {
                    Toast.makeText(getContext(), "开始时间大于结束时间", Toast.LENGTH_SHORT).show();
                    stopDate = myTimeTool.getToday();
                    selectTimeEnd.setText(myTimeTool.DateToString(stopDate));
                }
            }
        },calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
    }

    public Boolean judge(Date date1,Date date2)
    {
        int year1;
        int year2;
        int month1;
        int month2;
        int day1;
        int day2;
        myTimeTool.setDate(date1);
        year1 = myTimeTool.getYear();
        month1 = myTimeTool.getMonth();
        day1 = myTimeTool.getDay();

        myTimeTool.setDate(date2);

        year2 = myTimeTool.getYear();
        month2 = myTimeTool.getMonth();
        day2 = myTimeTool.getDay();

        if (year1 > year2)
        {
            return false;
        }
        else if (month1 > month2)
        {
            return false;
        }
        else if (day1 > day2)
        {
            return false;
        }
        else
        {
            return true;
        }
    }


    public void setChangeType(View view)
    {
        if (!flag)
        {
            flag = true;
            changeType.setText("收入");
            clearDate();
            setDate(accountManager.queryTime(startDate,stopDate));
        }
        else
        {
            flag = false;
            changeType.setText("支出");
            clearDate();
            setDate(accountManager.queryTime(startDate,stopDate));
        }
    }


    //初始化时间设置
    public void initDate()
    {
        startDate = myTimeTool.getFirstDate();
        stopDate = myTimeTool.getToday();

        //设置初始显示
        selectTimeBegin.setText(myTimeTool.DateToString(startDate));
        selectTimeEnd.setText(myTimeTool.DateToString(stopDate));

    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        update();
    }

    @Override
    public void setUserVisibleHint(boolean hidden)
    {
        // TODO Auto-generated method stub
        super.setUserVisibleHint(hidden);
        if (hidden)
        {
            update();
        }
    }

}
